package com.css.apps.base.user.action;

import com.css.apps.base.log.model.LogConstant;
import com.css.apps.base.log.model.LogPart;
import com.css.apps.base.user.model.SUser;
import com.css.apps.base.user.model.SUserRole;
import com.css.apps.base.user.service.UserHelper;
import com.css.core.configuration.Environment;
import com.css.db.query.QueryCache;
import com.css.db.query.TransactionCache;
import com.css.util.Ajax;
import com.css.util.Messages;
import com.css.util.StringHelper;
import com.css.webbase.webwork.action.AdminAction;
import com.opensymphony.xwork.Action;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.util.List;

@SuppressWarnings("serial")
public class DelUserRole extends AdminAction {
	private static Log log = LogFactory.getLog(DelUserRole.class);
	private String ids; // 角色uuid
	private String userId; // 用户uuid

	@SuppressWarnings("unchecked")
	@Override
	protected String adminGo() {
		TransactionCache tx = null;
		try {
			if (StringHelper.isEmpty(ids) || StringHelper.isEmpty(userId)) {
				result = Ajax.JSONResult(Environment.RESULT_CODE_ERROR, Messages.getString("systemMsg.fieldEmpty"));
				return Action.ERROR;
			}
			List<String> listIds = StringHelper.strToList(ids);
			//删除关联角色
			List<String> sUserRoleIds = new QueryCache(
					"select a.uuid from SUserRole a where a.userId= :userId and a.roleId in (:listIds) ")
							.setParameter("userId", userId).setParameter("listIds", listIds).list();
			List<SUserRole> roles = QueryCache.idToObj(SUserRole.class, sUserRoleIds);
			tx = new TransactionCache();
			tx.delete(SUserRole.class, sUserRoleIds);
			tx.commit();
			//同步缓存
			SUser usrObj = QueryCache.get(SUser.class, userId);
			usrObj.getRoleList().removeAll();
			new UserHelper().clearUserMenuCache(userId);
			//记录日志
			for (String userRoleId : sUserRoleIds) {
				LogPart lp = new LogPart();
				lp.setOpObjType(SUserRole.class.getName());
				lp.setOpObjId(userRoleId);
				lp.setRelObjType(SUser.class.getName());
				lp.setRelObjId(userId);
				lp.setOpType(LogConstant.LOG_TYPE_DELETE);
				lp.setLogLevel(LogConstant.LOG_LEVEL_IMPORTANT);
				lp.setLogData("");
				lp.setResult(LogConstant.RESULT_SUCCESS);
				lp.save();
			}
			result = Ajax.JSONResult(Environment.RESULT_CODE_SUCCESS, Messages.getString("systemMsg.success"));
			return Action.SUCCESS;
		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
			if (tx != null) {
				tx.rollback();
			}
			result = Ajax.JSONResult(Environment.RESULT_CODE_ERROR, Messages.getString("systemMsg.exception"));
			return Action.ERROR;
		}
	}

	public String getIds() {
		return ids;
	}

	public void setIds(String ids) {
		this.ids = ids;
	}

	public String getUserId() {
		return userId;
	}

	public void setUserId(String userId) {
		this.userId = userId;
	}

}
